package com.longway.common.kit;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jfinal.kit.StrKit;

/**
 * SqlKit
 */
public class SqlKit {
	
	private final static Logger log = LoggerFactory.getLogger(ClassKit.class);

	/**
	 * 将 id 列表 join 起来，用逗号分隔，并且用小括号括起来
	 */
	public static void joinIds(List<Integer> idList, StringBuilder ret) {
		ret.append("(");
		boolean isFirst = true;
		for (Integer id : idList) {
			if (isFirst) {
				isFirst = false;
			} else {
				ret.append(", ");
			}
			ret.append(id.toString());
		}
		ret.append(")");
	}
	
	public static boolean checkSQLInject(String str) {
		if (StrKit.isBlank(str)) {
			return false;// 如果传入空串则认为不存在非法字符
		}

		// 判断黑名单
		String[] inj_stra = { "script", "mid", "master", "truncate", "insert", "select", "delete", "update", "declare",
				"iframe", "'", "onreadystatechange", "alert", "atestu", "xss", ";", "'", "\"", "<", ">", "(", ")", ",",
				"\\", "svg", "confirm", "prompt", "onload", "onmouseover", "onfocus", "onerror","and","exec","execute"
				,"drop","*","%","chr","char","sitename","net user","xp_cmdshell",",","like'","create","create"
				,"from","grant","use","group_concat","column_name","information_schema.columns","table_schema","union"
				,"where","order","by","or","-","--","+","#"};//过滤掉的sql关键字，可以手动添加
		str = str.toLowerCase(); // sql不区分大小写
		for (int i = 0; i < inj_stra.length; i++) {
			if (str.indexOf(inj_stra[i]) >= 0) {
				log.info("xss防攻击拦截:原因：特殊字符，传入str=" + str + ",包含特殊字符：" + inj_stra[i]);
				return true;
			}
		}
		return false;
	}
}

